package yxy.game.pm2.command.stairway;

import yxy.cherry.data.bean.sportsdate;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.StairwayMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.stairway.StairwayHandle;
import yxy.game.pm2.module.stairway.StairwayPlayerModule;

/** 天梯争雄 天梯一键挑战 */
@MessageType(proto = Command.StairwayChanllengeQuick, classtype = StairwayMessage.StairwayChanllengeQuickRequest.class)
public class CMD_StairwayChanllengeQuick extends Command<StairwayMessage.StairwayChanllengeQuickRequest> {

	@Override
	public void execute(MessageSource messageSource, StairwayMessage.StairwayChanllengeQuickRequest request) {
		String playerCode = messageSource.getTag();

		StairwayMessage.StairwayChanllengeQuickResponse.Builder response = StairwayMessage.StairwayChanllengeQuickResponse.newBuilder();

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		boolean isOpen = StairwayHandle.isOpen(areaBean.getGroupId());
		if (!isOpen) {
			send(messageSource, response, Result.StairwayNotOpen);// 活动没有开始
			return;
		}

		if (!new StairwayHandle().checkArenaRank(playerCode)) {
			send(messageSource, response, Result.StairwayArenaRankNotFit);// 竞技场排名不够
			return;
		}

		StairwayPlayerModule stairwayPlayerModule = StairwayPlayerModule.get(playerCode);
		if (stairwayPlayerModule == null) {
			send(messageSource, response, Result.ModuleNotOpen);
			return;
		}
		
		// TODO 加锁
		Result result = new StairwayHandle().costTimes(stairwayPlayerModule);
		if (!result.equals(Result.Success)) {
			send(messageSource, response, result);
			return;
		}
		stairwayPlayerModule.set();

		Currencies rewards = new Currencies();
		sportsdate data = StairwayHandle.data();
		rewards.add(Currency.create(data.getWingettype(), data.getWingetid(), data.getWingetnum()));

		// 处理奖励
		new CurrencyHandle().addCurrency(playerCode, CCReason.天梯争雄, rewards);

		response.addAllRewards(new CurrencyHandle().packItems(rewards));
		response.setTimes(stairwayPlayerModule.remainTimes());
		response.setBuytimes(stairwayPlayerModule.remainBuyTimes());

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, StairwayMessage.StairwayChanllengeQuickResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}